package com.wang.back.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.wang.common.pojo.InfoEnum;
import com.wang.common.servlet.BaseServlet;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.common.util.PageInfoUtil;
import com.wang.users.pojo.AMenu;
import com.wang.users.pojo.ARole;
import com.wang.users.pojo.ARoleMenu;
import com.wang.users.service.IAuthDbService;
import com.wang.users.service.IUsersDbService;
import com.wang.users.service.impl.AuthDbServiceImpl;
import com.wang.users.service.impl.UsersDbServiceImpl;

/**
 * 授权的Servlet
 * 
 * @author Zjx
 *
 */
@WebServlet(urlPatterns = "/back/AuthBackServlet")
public class AuthBackServlet extends BaseServlet
{
	private IAuthDbService authDbService = new AuthDbServiceImpl();
	private IUsersDbService usersDbService = new UsersDbServiceImpl();
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		/**
		 * instanceof 
		 */
		if(this.usersDbService instanceof UsersDbServiceImpl)
		{
			UsersDbServiceImpl usersDbServiceImpl = (UsersDbServiceImpl) usersDbService ; 
			usersDbServiceImpl.setAuthDbService(authDbService);
		}
		
		if(this.authDbService instanceof AuthDbServiceImpl)
		{
			AuthDbServiceImpl authDbServiceImpl = (AuthDbServiceImpl) authDbService ; 
			authDbServiceImpl.setUsersDbService(usersDbService);
		}
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String method = request.getParameter("method");
		if("menuList".equalsIgnoreCase(method))
		{
			/* 菜单的平板结构
			 * 树顶的阳光直接大树我们看地上的影响(相当把树压平了)
			 *  */
			this.menuList(request,response);
		}else if("menuTreeList".equalsIgnoreCase(method))
		{
			/* 菜单的平板结构
			 * 树顶的阳光直接大树我们看地上的影响(相当把树压平了)
			 *  */
			this.menuTreeList(request,response);
		}else if("roleMenuInsertSubmit".equalsIgnoreCase(method))
		{
			this.roleMenuInsertSubmit(request,response);
		}else
		{
			this.blank(request, response);
		}
	}

	/**
	 * 授权提交
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void roleMenuInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		JSONObject resultJSON = new JSONObject();
		
		String roleId = request.getParameter("roleId");
		/* 1,2,3,5,6 */
		String menuIds = request.getParameter("menuIds");
		if(menuIds == null)
		{
			menuIds = "" ; 
		}
		
		if(!"".equalsIgnoreCase(menuIds))
		{
			/* 先删除原来角色中所有的菜单 */
			Map<String,Object> condMap = new HashMap<String, Object>();
			
			condMap.put("roleId", roleId);
			this.authDbService.deleteOneRoleMenuService(condMap);
			
			/* 按照逗号拆分 */
			String[] menuIdss = menuIds.split(",");
			
			int totalCount = menuIdss.length ; 
			int succedCount = 0 ; 
			int failedCount = 0 ; 
			
			for(String idTemp : menuIdss)
			{
				/* 入库 */
				ARoleMenu roleMenu = new ARoleMenu();
				
				roleMenu.setMenuId(Integer.valueOf(idTemp));
				roleMenu.setRoleId(Integer.parseInt(roleId));
				roleMenu.setStatus(Byte.valueOf("1"));
				roleMenu.setPubTime(new Date());
				
				JSONObject resultDbJSON = this.authDbService.saveOneRoleMenuService(roleMenu);
				/* 0 = 0 */
				if(resultDbJSON.get(InfoEnum.VAR_CODE.getInfo() + "").equals(InfoEnum.INFO_SUCCESS.getCode()))
				{
					/* 成功 */
					succedCount ++ ; 
				}else
				{
					failedCount ++ ;
				}
			}
			
			resultJSON.put("code", InfoEnum.INFO_SUCCESS.getCode());
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get(InfoEnum.INFO_SUCCESS.getCode() + ""));
			
			JSONObject dataResJSON = new JSONObject();
			dataResJSON.put("totalCount", totalCount);
			dataResJSON.put("succedCount", succedCount);
			dataResJSON.put("failedCount", failedCount);
			
			resultJSON.put("data", dataResJSON);
		}else
		{
			resultJSON.put("code", "-2");
			resultJSON.put("info", "请选择菜单");
		}
		System.out.println("==授权==" + resultJSON.toJSONString());
		
		this.printStr(request, response, resultJSON.toJSONString());
		
	}

	/**
	 * 树形结构,不能分页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void menuTreeList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==menuTreeList==");
		
		Map<String,Object> condMap = new HashMap<String, Object>();
		List<AMenu> menuList = this.authDbService.findCondListMenuService(null,condMap);
		/* 存储四大作用域 */
		request.setAttribute("list", menuList);
		String path = "/back/auth/menuTreeList" ; 
		
		String roleId = request.getParameter("roleId");
		if(roleId != null && !"".equalsIgnoreCase(roleId))
		{
			/* 根据id查询角色 */
			condMap.clear();
			condMap.put("id", roleId);
			ARole role = this.usersDbService.findOneRoleService(condMap);
			request.setAttribute("role", role);
			
			PageInfoUtil pageInfoUtil = new PageInfoUtil();
			
			/* 循环menuList;根据roleId和menuId到a_role_menu表查询,如果查询到,说明已经权限,默认选中 */
			for (AMenu menuTemp : menuList)
			{
				condMap.clear();
				condMap.put("roleId", role.getId());
				condMap.put("menuId", menuTemp.getId());
				this.authDbService.findCondListRoleMenuService(pageInfoUtil, condMap);
				if(pageInfoUtil.getTotalRecord() > 0 )
				{
					/* 说明查询到了 */
					menuTemp.setCheckStr("1");
				}
			}
			
			/* 授权页面 */
			path = "/back/auth/menuTreeAuthList" ; 
		}
		this.serverRedirect(request, response, path);
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void menuList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==menuList==");
		
		/* 分页工具类 */
		PageInfoUtil pageInfoUtil = proccedPageInfoUtil(request);
		/* 处理搜索条件 */
		Map<String, Object> condMap = proccedSearchCond(request);
		
		/* ==状态处理开始== */
		String parentId = request.getParameter("parentId");
		if(parentId == null)
		{
			parentId = "" ; 
		}
		condMap.put("parentId", parentId);
		request.setAttribute("parentId", parentId);
		/* ==状态处理结束== */
		
		condMap.put("extend", "true");
		List<AMenu> menuList = this.authDbService.findCondListMenuService(pageInfoUtil,condMap);
		/* 存储四大作用域 */
		request.setAttribute("list", menuList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		
		/* 查询整棵树形结构
		 * 在管理员列表中查询所有的角色一样
		 *  */
		List<AMenu> menuTreeList = this.authDbService.findCondListTreeMenuService(0, null);
		request.setAttribute("menuTreeList", menuTreeList);
		
		this.serverRedirect(request, response, "/back/auth/menuList");
	}
}
